/**
 * 
 */
package cn.jupiter.servlet;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.jupiter.db.DbUtils;
import cn.jupiter.json.RestResource;
import cn.jupiter.json.ResultSetJson;

/**
 * @author pizhenhua@gmail.com
 *
 */
public class GetTypeWorker implements ITypeWork{
	private final String FIND_BY_SQL="findbysql";
	private final String FIND_BY_ID="index";
	private final String GET_TYPE="type";
	protected final Log log = LogFactory.getLog(GetTypeWorker.class);
	//���ݴ������
	private PrintWriter writer=null;
	private HttpServletRequest request=null;
	//
	public GetTypeWorker(HttpServletRequest request,PrintWriter writer){
		this.writer=writer;
		this.request=request;
	}
	public void execute(){
		String type=request.getParameter(this.GET_TYPE);
		ResultSetJson json=null;
		Connection conn=null;
		String url =request.getRequestURL().toString();
		RestResource r;
		log.debug("get method,type is :"+request.getParameter(this.GET_TYPE));
		//find by sql
		if(this.FIND_BY_SQL.endsWith(type)){
			String sql=request.getParameter("sql");
			log.info("client request:find by sql,sql:"+sql);
			r=new RestResource();
			r.setSql(sql);
		}
		if(FIND_BY_ID.endsWith(type)){
			//如果有id，按id返回，没有，返回全部
			r= RestUrlParser.parserUrl(url);
			if(request.getParameter("id")==null){
				r.setSql("select * from "+r.getResouce());
			}
			else{
				r.setSql("select * from "+r.getResouce()+" where id="+request.getParameter("id"));
			}
			
			
		}
		else{
			r= RestUrlParser.parserUrl(url);
		}
		


		try {
			conn=DbUtils.getConn();
			json=new ResultSetJson(conn,r);
			json.setJSON_TYPE(ResultSetJson.JSON_TYPE_2);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println(json.toJson());
	}
}
